﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Animation;
using System.Windows.Threading;

namespace KxApp.Views
{
    /// <summary>
    /// TableView.xaml 的交互逻辑
    /// </summary>
    public partial class TableView : UserControl
    {
        public TableView()
        {
            InitializeComponent();
        }

        private DispatcherTimer scrollTimer;
        private ScrollViewer scrollViewer;
        private double scrollHeight;
        private bool isScrollingDown = true;
        private const double ScrollStep = 1.0; // 每次滚动的像素
        private const int ScrollInterval = 500; // 滚动间隔(毫秒)

        private void DataGrid_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            // 获取DataGrid内部的ScrollViewer
            //scrollViewer = FindVisualChild<ScrollViewer>(dataGrid);

            if (scrollViewer != null)
            {
                // 初始化滚动高度
                scrollHeight = scrollViewer.ExtentHeight - scrollViewer.ViewportHeight;

                // 设置定时器
                scrollTimer = new DispatcherTimer();
                scrollTimer.Interval = TimeSpan.FromMilliseconds(ScrollInterval);
                scrollTimer.Tick += ScrollTimer_Tick;
                scrollTimer.Start();
            }
        }

        private void DataGrid_Unloaded(object sender, System.Windows.RoutedEventArgs e)
        {
            // 清理定时器
            if (scrollTimer != null)
            {
                scrollTimer.Stop();
                scrollTimer.Tick -= ScrollTimer_Tick;
                scrollTimer = null;
            }
        }

        private void ScrollTimer_Tick(object sender, EventArgs e)
        {
            if (scrollViewer == null)
                return;

            // 向下滚动
            scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset + ScrollStep);

            // 检查是否滚动到底部
            if (scrollViewer.VerticalOffset >= scrollHeight)
            {
                // 立即回到顶部，实现循环滚动
                scrollViewer.ScrollToVerticalOffset(0);
            }
        }

        // 辅助方法：查找子控件
        private static T FindVisualChild<T>(DependencyObject obj)
            where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                var child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is T)
                    return (T)child;
                else
                {
                    var childOfChild = FindVisualChild<T>(child);
                    if (childOfChild != null)
                        return childOfChild;
                }
            }
            return null;
        }
    }
}
